package br.com.d2g.realestate.listener;


import br.com.d2g.realestate.controller.UserController;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 *
 * @author diego
 */ 
public class LoggedInCheck implements PhaseListener {
 
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
 
    public void beforePhase(PhaseEvent event) {
    }
   
    public void afterPhase(PhaseEvent event) {
        FacesContext fc = event.getFacesContext();
 
        // Check to see if they are on the login page.
//        fc.getViewRoot().g;
        boolean loginPage = fc.getViewRoot().getViewId().lastIndexOf("login") > -1 ? true : false;
        boolean registerPage = fc.getViewRoot().getViewId().equals("/Register.xhtml") ? true : false;
        boolean registerPageAgent = fc.getViewRoot().getViewId().equals("/RegisterAgent.xhtml") ? true : false;
        boolean registerPageOwner = fc.getViewRoot().getViewId().equals("/RegisterOwner.xhtml") ? true : false;
        if (!loginPage && !loggedIn() && !registerPage && !registerPageAgent && !registerPageOwner) {
            NavigationHandler nh = fc.getApplication().getNavigationHandler();
            nh.handleNavigation(fc, null, "logout");
        }
        //test roles in session variables to redirect out of a place
    }
 
    private boolean loggedIn() {
        return UserController.loggedIn();
    }
    

}